import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { NavigationExtras, Router } from '@angular/router';

import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';

import { ChartComponent } from '../shared/components/chart/chart.component';
import { UserService } from './shared/user.service';
import { UserLoadStateService } from './shared/user-load-state.service'
import { CommonService } from '../core/services/common.service';
import { MaterialDialogService } from '../core/services/material-dialog.service';
import { BaseDirective } from '../core/models/base-directive.model';
import { UserGeneralConfig } from '../core/config/user-general.config';
import { MaterialPanelComponent } from '../extensions/elements/panels/material-panel/material-panel.component';
import { PanelOption } from '../extensions/elements/panels/shared/models/panel-option.model';

@Component({
    selector: 'op-users',
    templateUrl: './users-demo.component.html'
})
export class UsersDemoComponent extends BaseDirective implements OnInit {
    @ViewChild('nationalityComponent', {static: false}) nationalityComponent: ChartComponent;
    @ViewChild('statusComponent', {static: false}) statusComponent: ChartComponent;
    @ViewChild('treeComponent', {static: false}) treeComponent: ChartComponent;
    @ViewChild('nationalityPanelComponent', {static: false}) nationalityPanelComponent: MaterialPanelComponent
    @ViewChild('statusPanelComponent', {static: false}) statusPanelComponent: MaterialPanelComponent;
    @ViewChild('treePanelComponent', {static: false}) treePanelComponent: MaterialPanelComponent;
    private isUserStatisticTabLoaded: boolean = false;
    nationalityPanel: PanelOption;
    statusPanel: PanelOption;
    treePanel: PanelOption;
    searchData: Object;
    users: any = [];
    nationality: Object;
    status: Object;
    tree: Object;
    chart: any;
    userName: string = null;
    fristDialog: string = null;
    secondDialog: string = null;
    userData: any[];
    constantOfStatus = UserGeneralConfig.status;
    constantOfNation = UserGeneralConfig.nationality;

    constructor(
        private userService: UserService,
        private userLoadStateService: UserLoadStateService,
        private router: Router,
        private elementRef: ElementRef,
        private dialog: MatDialog,
        private materialDialogService: MaterialDialogService
    ) { super(); }

    ngOnInit(): void {
        super.ngOnInit();

        this.loadChartPanel();
        this.displayChartsData();
        this.getSearchData(null);
        this.getUsers(this.searchData);
    }

    // 列表显示
    getUsers(searchData: any): void {
        this.userService.getUserList(searchData).subscribe(data => {
            this.userData = data.result;
            if (searchData) {
                if (searchData.status) {
                    let status = searchData.status;
                    this.userData = this.userData.filter(user => user.status === status);
                }

                if (searchData.userName) {
                    this.userData = this.userData.filter(user => user.name.indexOf(searchData.userName) >= 0);
                }

                if (searchData.startDate) {
                    this.userData = this.userData.filter(user => new Date(user.birthday) >= new Date(searchData.startDate));
                }

                if (searchData.endDate) {
                    this.userData = this.userData.filter(user => new Date(user.birthday) <= new Date(searchData.endDate));
                }
            }
            this.users = this.userData;
        });
    }

    // // 列表显示
    // getUsers(searchData: any): void {
    //     this.userService.getUserList(searchData).subscribe(data => {
    //         this.users = data.result;
    //     });
    // }

    // 获得搜索框的内容
    getSearchData(event: any): void {
        this.searchData = event;

        if (event) {
            this.userName = event.userName;
        }

        this.getUsers(this.searchData);
    }

    // 查看用户详情
    showUserDetails(id: number): void {
        this.router.navigate(['/users/detail', id]);
    }

    // 修改用户信息
    edit(id: number): void {
        this.router.navigate(['/users/edit', id]);
    }

    // 数据统计
    displayChartsData(): void {
        this.userService.getEchartsNationalityData(this.constantOfNation).subscribe(data => {
            this.nationality = this.echartsNationalityData(data);
        });

        this.userService.getEchartsStatusData(this.constantOfStatus).subscribe(data => {
            this.status = this.echartsStatusData(data);
        });

        // this.userService.getEchartsNationalityData(this.constantOfNation).subscribe(data => {
        //     let countList: number[] = [];
        //     let descriptionList: string[] = [];

        //     data.result.forEach(item => {
        //         countList.push(item.count);
        //         descriptionList.push(item.description);
        //     });

        //     let nationality = {
        //         x: descriptionList,
        //         value: countList,
        //         name: '民族'
        //     };
        //     this.nationality = this.echartsNationalityData(nationality);
        // });

        // this.userService.getEchartsStatusData(this.constantOfStatus).subscribe(data => {
        //     let nameList: string[] = [];

        //     data.result.forEach(item => {
        //         nameList.push(item.name);
        //     });

        //     let status = {
        //         value: data.result,
        //         name: nameList,
        //         text: '人生状态'
        //     };
        //     this.status = this.echartsStatusData(status);
        // });

        this.userService.getEchartsTreeData().subscribe(data => {
            this.tree = this.echartsTreeData(data);
        });
    }

    loadChartPanel(): void {
        this.nationalityPanel = {
            expanded: false,
            height: '50px',
            title: '柱状图',
            description: null,

        };

        this.statusPanel = {
            expanded: true,
            height: '50px',
            title: '饼状图',
            description: null,
        };

        this.treePanel = {
            expanded: true,
            height: '50px',
            title: '树状图',
            description: null,
        };
    }

    showChart(event: any): void {
        if (event.tab.textLabel === "Panel&Echarts") {
            this.nationalityComponent.resize();
            this.statusComponent.resize();
            this.treeComponent.resize();
            this.nationalityPanelComponent.hidingPanelBody();
        }
    }

    echartsNationalityData(data: any): object {
        let option = {
            color: ['#3398DB'],
            title: {
                text: data.name,
                subtext: null,
                left: 'center'
            },
            toolbox: {
                show: true,
                left: 'center',
                top: '8%',
                feature: {
                    magicType: { show: true, type: ['line', 'bar'] },
                    saveAsImage: { show: true }
                }
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'line'
                }
            },
            grid: {
                left: '5%',
                right: '5%',
                bottom: '5%',
                containLabel: true
            },
            xAxis: [
                {
                    type: 'category',
                    data: data.x,
                    axisTick: {
                        alignWithLabel: true
                    }
                }
            ],
            yAxis: [
                {
                    type: 'value'
                }
            ],
            series: [
                {
                    name: data.name,
                    type: 'bar',
                    barWidth: '60%',
                    data: data.value,
                    markLine: {
                        data: [
                            { type: 'average', name: '平均值' }
                        ]
                    }
                }
            ]
        };
        return option;
    }

    echartsStatusData(data: any): object {
        let option = {
            title: {
                text: data.text,
                subtext: null,
                x: 'center'
            },
            toolbox: {
                show: true,
                left: 'center',
                top: '8%',
                feature: {
                    saveAsImage: { show: true }
                }
            },
            tooltip: {
                trigger: 'item',
                formatter: "{a} <br/>{b} : {c} ({d}%)"
            },
            legend: {
                orient: 'vertical',
                left: 'left',
                data: data.name
            },
            series: [
                {
                    name: data.text,
                    type: 'pie',
                    radius: '55%',
                    center: ['50%', '60%'],
                    data: data.value,
                    itemStyle: {
                        emphasis: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                    }
                }
            ]
        };
        return option;
    }

    echartsTreeData(data: any): object {
        let option = {
            title: {
                text: '民族分布状况',
                subtext: null,
                left: 'center'
            },
            tooltip: {
                trigger: 'item',
                triggerOn: 'mousemove'
            },
            toolbox: {
                show: true,
                left: 'center',
                top: '8%',
                feature: {
                    saveAsImage: { show: true }
                }
            },
            series: [
                {
                    type: 'tree',
                    data: [data],

                    top: '5%',
                    left: '12%',
                    bottom: '5%',
                    right: '10%',

                    symbolSize: 6,
                    initialTreeDepth: 10,

                    label: {
                        normal: {
                            position: 'left',
                            verticalAlign: 'middle',
                            align: 'right',
                            fontSize: 9
                        }
                    },

                    leaves: {
                        label: {
                            normal: {
                                position: 'right',
                                verticalAlign: 'middle',
                                align: 'left'
                            }
                        }
                    },

                    expandAndCollapse: true,
                    animationDuration: 550,
                    animationDurationUpdate: 750
                }
            ]
        };
        return option;
    }
}